let fs =  require("fs");
let image = require("imageinfo");
//引用images模块
var images = require('images');
var watermarkImg = images('butterfly.png');

let strRootPath = "E:/workCode/HBEducation/EducationGuanLin";
/**
 * 遍历文件路径
 * @param {*} strPath 文件路径
 * @param {*} aFileList 文件存储数组
 * @param {*} aImageList 图片文件存储数组
 */
let traverse = (strPath, aFileList, aImageList) => {
    let files = fs.readdirSync(strPath);
    files.forEach(function(strFileName, index){
        let strCurPath = `${strPath}/${strFileName}`;
        let stat = fs.statSync(strCurPath);
        if(stat.isDirectory()){
            traverse(strCurPath, aFileList, aImageList);
        }else{
            var ms = image(fs.readFileSync(strCurPath));
            
            let o = {
                path : strCurPath,
                name : strFileName
            }
            if(ms){
                o = Object.assign(ms, o);
                aImageList.push(o);
            }
            aFileList.push(o);
        }
    });
}


/**
 * 遍历文件找到所有使用并存在的图片
 * @param {文件列表} aFile 
 */
let checkUsedImage = (aFile)=> {
    let aUsedImage = [];
    aFile.forEach((obj, index)=>{
        if(obj.type&&obj.type == "image"){
    
        }else{
            
            let data = fs.readFileSync(obj.path);
            let str = data.toString();
            let aLines = str.split("\n");
            aLines.forEach((strLine,index)=>{
                let aPath = obj.path.split("/");
                let strLast =aPath.pop();
                let re = strLine.match(/(('|"|\()([^'"\(]+\.jpg))|(('|"|\()([^'"\(]+\.png))/g);
                if(re){
                    re.forEach((strPath)=>{
                        let strPath2 = strPath.substr(1);
                        
                        let r = strPath2.match(/\.\.\//g);
                        let strPath3;
                        
                        if(r&&r.length){
                            
                            for(let i = 0; i < r.length; i++){
                                aPath.pop();
                            }
                            strPath3 = `${aPath.join("/")}/${strPath2.replace(/\.\.\//g,"")}`;
                            //console.log(strPath3);
                        }else{
                            if(0 == strPath2.indexOf("./")){
                                strPath3 = aPath.join("/") + strPath2.substr(1);
                            }else if(0 == strPath2.indexOf("/")){
                                strPath3 =  strRootPath + strPath2;
                            }else{
                                if(strLast == "layout.js"){
                                    aPath.pop();
                                }
                                strPath3 =  `${aPath.join("/")}/${strPath2}`;
                                // console.log(strPath3);
                            }
                        }
                        if(fs.existsSync(strPath3)){
                            aUsedImage.push(strPath3);
                        }
                    });
                }
            });
        }
        
    })
    return aUsedImage;
}

/**
 * 遍历找出未使用到的图片路径
 */
let checkUnusedImages = (arrUsed, arrImage)=> {
    let arr = [];
    arrImage.forEach((item, index)=>{
        if(-1 == arrUsed.indexOf(item.path)){
            arr.push(item.path);
            
        }
    });
    return arr;
}
let embedWatermark = (arrImage, strSavePath) => {
    if(fs.existsSync(arrImage)){
        let strPath = arrImage;
        arrImage = [];
        traverse(strPath, [], arrImage);
    }
   
    if(!(arrImage instanceof Array)){
        console.log("未检测到图片列表");
        return;
    }
    strSavePath = strSavePath || `./saveImg`;
    if(fs.existsSync(strSavePath)){

    }else{
        fs.mkdirSync(strSavePath);
    }
    //获取文件夹下的所有图片
    let len = arrImage.length;
    let iCount = 0;
    for (var i = 0; i < len ; i++) {
        try {
            
            if(!arrImage[i].format || arrImage[i].format == "GIF" || arrImage[i].format == "JFIF"){
                console.log(arrImage[i].path);
            }else{
                var sourceImg = images(arrImage[i].path);
                var sourceImgName = arrImage[i].name;
                var sWidth = sourceImg.width();
                var sHeight = sourceImg.height();
                var wmWidth = watermarkImg.width(40);//把图片缩放成40的尺寸大小
                var wmHeight = watermarkImg.height(40);
                images(sourceImg)
                
                // 设置绘制的坐标位置，右下角距离 40px
                .draw(watermarkImg, sWidth - 40, sHeight - 40)
                // 保存格式会自动识别
                .save(`${strSavePath}/${sourceImgName}`);
                iCount++;
            }
            
        } catch (error) {
            console.log("error==>"+error);
        }
        
    }
    console.log(iCount + "/" + len);
}
/**
 * 删除无用图片
 */
let deleteUnusedImgs = ()=> {
    //执行
    let aFileList = [];
    let aImageList = [];
    traverse(strRootPath, aFileList, aImageList);
    let arrUnused = checkUnusedImages(checkUsedImage(aFileList),aImageList);
    // console.log("-------------------分割线------------------");
    // console.log(arrUnused);
    //删除无用文件
    arrUnused.forEach((strPath)=>{
        console.log("删除路径"+strPath);
        fs.unlinkSync(strPath);
    });
}

embedWatermark("E:/文档/教育/互动教育/学校通用分类页切图/推荐位图","testImg");